package org.wattdepot.cli.commands;

import java.util.List;
import javax.xml.datatype.XMLGregorianCalendar;
import org.wattdepot.client.BadXmlException;
import org.wattdepot.client.MiscClientException;
import org.wattdepot.client.NotAuthorizedException;
import org.wattdepot.client.ResourceNotFoundException;
import org.wattdepot.client.WattDepotClient;
import org.wattdepot.util.tstamp.Tstamp;

/**
 * Provides the command to obtain the total generated carbon/energy.
 * 
 * @author David Joel Lazaro
 */
public class TotalGenerated implements Command {

  /**
   * Calls the totalGenerated method.
   * 
   * @param userInput The user input.
   * @param client The WattDepotClient
   * @return Returns the method call with the proper parameters.
   */
  public String doCommand(List<String> userInput, WattDepotClient client) {
    return totalGenerated(userInput, client);
  }

  /**
   * Prints the total mount of carbon (or energy) generated by a source for the given day.
   * 
   * @param commandParam The input from user.
   * @param client The WattDepotClient
   * @return Returns the total carbon/energy generated.
   */
  private String totalGenerated(List<String> commandParam, WattDepotClient client) {
    StringBuffer buff = new StringBuffer();
    SourceChecker check = new SourceChecker();
    TStampChecker stampCheck = new TStampChecker();
    if (!check.sourceChecker(commandParam.get(3), client)) {
      return "";
    }

    if (!stampCheck.checkTStamp(commandParam.get(5))) {
      return "ERROR: Timestamp error.";
    }

    try {
      int interval = Integer.parseInt(commandParam.get(7));
      XMLGregorianCalendar start = Tstamp.makeTimestamp(commandParam.get(5));
      XMLGregorianCalendar end = Tstamp.incrementDays(start, 1);
      end = Tstamp.incrementMinutes(end, interval);

      if (commandParam.get(1).equalsIgnoreCase("carbon")) {
        double carbonEmitted = client.getCarbonEmitted(commandParam.get(3), start, end, interval);
        System.out.println(carbonEmitted);
      }
      else if (commandParam.get(1).equalsIgnoreCase("energy")) {
        double energyConsumed =
            client.getEnergyGenerated(commandParam.get(3), start, end, interval);
        System.out.println(energyConsumed);
      }
    }

    catch (NotAuthorizedException e) {
      e.printStackTrace();
    }
    catch (ResourceNotFoundException e) {
      System.out.println("Error: Requested timestamp " + commandParam.get(5) + " for the source "
          + commandParam.get(3) + " not found.");
      return "";
    }
    catch (BadXmlException e) {
      e.printStackTrace();
    }
    catch (MiscClientException e) {
      e.printStackTrace();
    }
    catch (Exception e) {
      e.printStackTrace();
    }

    return buff.toString();
  }
}
